// web/src/app/api/(social)/messages/route.ts

import {NextRequest, NextResponse} from "next/server";
import {db} from "@/lib/db";

export async function GET(
    req: NextRequest
) {
    const searchParams = req.nextUrl.searchParams
    const _page = searchParams.get('_page')!
    const _per_page = searchParams.get('_per_page')!
    const channelId = searchParams.get('channelId')
    const conversationId = searchParams.get('conversationId')
    const parentMessageId = searchParams.get('parentMessageId')

    try {
        let where: {
            channelId: string | undefined
            conversationId: string | undefined
            parentMessageId: string | undefined
        } = {
            channelId: undefined,
            conversationId: undefined,
            parentMessageId: undefined,
        }
        if (channelId) where['channelId'] = channelId
        if (conversationId) where['conversationId'] = conversationId
        if (parentMessageId) where['parentMessageId'] = parentMessageId

        console.log('get messages api', where)
        const messages = await db.message.findMany({
            skip: (parseInt(_page) - 1) * parseInt(_per_page),
            take: parseInt(_per_page),
            where,
            include: {
                member: {
                    include: {
                        user: true
                    }
                },
                relation: {
                    include: {
                        // @ts-ignore
                        RelationMemberIds: true
                    }
                },
                reaction: true
            }
        })
        return NextResponse.json(messages)
    } catch (e) {
        console.error(e)
        return new NextResponse('Internal Server Error', {status: 500});
    }
}

export async function POST(
    req: NextRequest
) {
    const {threadCount, threadImage, threadTimestamp, ...values} = await req.json()
    console.log('create message: ', values)
    try {
        // 创建新消息, 设置parentMessageId
        const messages = await db.message.create({
            data: values
        })
        // 父级消息更新回复数...
        const updateMessage = await db.message.update({
            where: {id: values.parentMessageId},
            data: {
                threadCount, threadImage, threadTimestamp,
            }
        })
        return NextResponse.json(messages)
    } catch (e) {
        console.error(e)
        return new NextResponse('Internal Server Error', {status: 500});
    }
}